/**
 * 
 */
package cyclopean.world;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import cyclopean.world.actor.Pawn;
import cyclopean.world.actor.Walker;
import cyclopean.world.zone.Position;
import cyclopean.world.zone.Zone;
import cyclopean.world.zone.Zone.UpdateLevel;
import javagame.core.main.Time;

// TODO Javadoc
/**
 * 
 *
 * @author Jaco van der Westhuizen
 */
public class World
{
	private static World instance = null;
	
	private World()
	{
	}
	
	Zone[] zones = new Zone[] {new Zone()};

	public static synchronized void update(Time time)
	{
		for (Zone zone : instance.zones)
		{
		    // TODO Calculate update level
		    zone.update(time, UpdateLevel.LIVE);
		}
	}

    public static synchronized void generate()
    {
		if (instance == null)
			instance = new World();
		else
			throw new IllegalStateException("There may be only one world at a time.");

		// TODO Generate world
    }

    public static synchronized void load(String path)
    {
    	final File dir = new File(path);
    	
    	if (!dir.isDirectory())
    		throw new IllegalArgumentException("Path '" + path + "' is not a save game directory.");
    	
    	// TODO Load world
    }

    public static synchronized void save(String path) throws FileNotFoundException, IOException
    {
    	final File dir = new File(path);
    	
    	if (!dir.isDirectory())
    		throw new IllegalArgumentException("Path '" + path + "' is not a save game directory.");

    	final FileOutputStream writer = new FileOutputStream(dir.getPath() + "zones.dat");

    	for (Zone zone : instance.zones)
    	{
    		zone.save(writer);
    	}
    }
    
    public static synchronized void destroy()
    {
    	instance = null;
    }

    public static Pawn spawnPlayerPawn()
    {
    	if (instance == null)
    		throw new IllegalStateException("World does not exist.");

    	// TODO Player spawn points
    	Position p = new Position(instance.zones[0], 5f, 5f, 11.5f);
		p.setAngles((float)(Math.PI / 4), -(float)(Math.PI / 4));

		// TODO Human class
		return Zone.spawn(Walker.class, p);
    }
}
